//
//  ViewController.m
//  OpenGLES-Test
//
//  Created by huge on 2021/6/16.
//  Copyright © 2021 huge. All rights reserved.
//

#import "ViewController.h"
#import "AVCAEAGLLayer.h"
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#import "GLESView.h"

@interface ViewController ()
{
    EAGLContext* _eaglContext;
    AVCAEAGLLayer* _layer;
    GLuint _colorRenderBuffer;
    GLuint _frameBuffer;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createGLESView];
    
    
//    UIView* testView = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
//    testView.backgroundColor = [UIColor redColor];
//    [self.view addSubview:testView];
//
//    [self CreateGLView];
//    [self bindRenderFrameBuffer];
//    [self render];
}

-(void)createGLESView{
    GLESView* glView = [[GLESView alloc]initWithFrame:self.view.frame];
    [self.view addSubview:glView];
}

- (void)CreateGLView{
    
    //初始化上下文
    _eaglContext =[[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2];
    [EAGLContext setCurrentContext:_eaglContext];
    
    //初始化 layer
    _layer = [[AVCAEAGLLayer alloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height)];
    [self.view.layer addSublayer:_layer];
}

- (void)bindRenderFrameBuffer{
    
    glGenRenderbuffers(1,&_colorRenderBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER,_colorRenderBuffer);
    [_eaglContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:_layer];
    
    glGenFramebuffers(1, &_frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);
    
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0
                              , GL_RENDERBUFFER, _frameBuffer);}

- (void)render{
    
    glClearColor(0.0f, 0.9f, 0.9f, 1.0f);
    
    glClear(GL_COLOR_BUFFER_BIT);
    [_eaglContext presentRenderbuffer:GL_RENDERBUFFER];
}

@end
